package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.mapper.vo.PicUploadResult;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
@Service
public class QuanZiService {
    @Reference(version = "1.0.0",check = false)
    QuanZiApi quanZiApi;
    @Autowired
    UserService userService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    QuanZiService quanZiService;
    @Reference(version = "1.0.0",check = false)
    VisitorsApi visitorsApi;
    @Autowired
    private QuanziMQService quanziMQService;


    public PageResult queryPublishList(Integer page, Integer pageSize, String token) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.getuser();
        PageInfo<Publish> userPageInfo =quanZiApi.queryPublishList(user.getId(),page,pageSize);
        List<Publish> records = userPageInfo.getRecords();
        if (records==null) {
            return pageResult;
        }
        return fillQuanZiVo(pageResult, records);

    }

    /**
     * 将publish内容copy到quanzivo中
     * @param pageResult
     * @param records
     * @return
     */

    private PageResult fillQuanZiVo(PageResult pageResult, List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZivo = new QuanZiVo();
            quanZivo.setId(publish.getId().toHexString());
            quanZivo.setTextContent(publish.getText());
            quanZivo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZivo.setUserId(publish.getUserId());

            quanZivo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVoList.add(quanZivo);

        });
        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if(quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()){
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        pageResult.setItems(quanZiVoList);
        return pageResult;
    }

    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo){
        User user = UserThreadLocal.getuser();
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
        quanZiVo.setAvatar(userInfo.getLogo());
        quanZiVo.setNickname(userInfo.getNickName());
        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(),quanZiVo.getId())?1:0); //TODO 是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(quanZiApi.queryLikeCount(quanZiVo.getId()))); //TODO 点赞数
        quanZiVo.setHasLoved(quanZiApi.queryUserIsLove(user.getId(),quanZiVo.getId())?1:0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(quanZiApi.queryLoveCount(quanZiVo.getId()))); //TODO 喜欢数
    }


    @Autowired
    private PicUploadService picUploadService;

    /**
     * 发布动态
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile
     * @return
     */
    public String savePublish(String textContent,
                              String location,
                              String latitude,
                              String longitude,
                              MultipartFile[] multipartFile) {
        //查询当前的登录信息
        User user = UserThreadLocal.getuser();
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);

        List<String> picUrls = new ArrayList<>();
        //图片上传
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }
        String publishId = this.quanZiApi.savePublish(publish);
        if(StrUtil.isNotEmpty(publishId)){
            //发送消息
            this.quanziMQService.publishMsg(publishId);
        }

        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    /**
     * 查询推荐用户朋友圈
     * @param page
     * @param pageSize
     * @return
     */

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.getuser();
        PageInfo<Publish> publish = quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = publish.getRecords();
        if(records==null)
            return pageResult;
        return fillQuanZiVo(pageResult,records);
    }

    /**
     * 动态点赞
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        Long aLong = null;
        try {
            User user = UserThreadLocal.getuser();
            Boolean aBoolean = quanZiApi.likeComment(user.getId(), publishId);
            if(aBoolean)
            { aLong = quanZiApi.queryLikeCount(publishId);
            quanziMQService.likePublishMsg(publishId);}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aLong;
    }

    /**
     * 取消点赞
     * @param publishId
     * @return
     */
    public Long dislikeComment(String publishId) {
        Long aLong = null;
        try {
            User user = UserThreadLocal.getuser();
            Boolean aBoolean = quanZiApi.disLikeComment(user.getId(), publishId);
            if(aBoolean)
            {  aLong = quanZiApi.queryLikeCount(publishId);
            quanziMQService.disLikePublishMsg(publishId);}
        } catch (Exception e) {
            e.printStackTrace();

        }
        return aLong;

    }


    /**
     * 点赞评论
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        Long aong=null;
        try {

            User user = UserThreadLocal.getuser();
            Boolean aBoolean = quanZiApi.loveComment(user.getId(), publishId);
            if(aBoolean)
            { aong = quanZiApi.queryLoveCount(publishId);
            quanziMQService.lovePublishMsg(publishId);}
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return aong;

    }

    /**
     * 取消点赞评论
     * @param publishId
     * @return
     */
    public Long disLoveComment(String publishId) {
        Long ang=null;
        try {

            User user = UserThreadLocal.getuser();
            Boolean aBoolean = quanZiApi.disLoveComment(user.getId(), publishId);
            if(aBoolean)
            { ang = quanZiApi.queryLoveCount(publishId);
            quanziMQService.disLovePublishMsg(publishId);}
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return ang;

    }

    /**
     * 根据id查询动态
     * @param publishId
     * @return
     */
    public QuanZiVo queryById(String publishId) {
        Publish publish = quanZiApi.queryPublishById(publishId);
        if(publish==null)
            return null;
        quanziMQService.queryPublishMsg(publishId);
        PageResult pageResult = new PageResult();
        ArrayList<Publish> publishes = new ArrayList<>();
        publishes.add(publish);
        PageResult pageResult1 = fillQuanZiVo(pageResult, publishes);
        List<?> items = pageResult1.getItems();
        QuanZiVo o = (QuanZiVo) items.get(0);
        return o;


    }
    /**
     * 发表评论
     * @param publishId
     * @param content
     * @return
     */
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.getuser();
        boolean a=quanZiApi.saveComment(user.getId(), publishId, content);
        if(a)
        {quanziMQService.commentPublishMsg(publishId);}
        return a;
    }

    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        User user = UserThreadLocal.getuser();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Comment> comment = quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = comment.getRecords();
        ArrayList<CommentVo> commentVos = new ArrayList<>();
        if(CollUtil.isEmpty(records))
            return pageResult;
        List<Object> userId = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(userId);
        for (Comment record:records) {
            CommentVo commentVo = new CommentVo();
            commentVo.setContent(record.getContent());
            commentVo.setId(record.getId().toHexString());
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(commentVo.getId())));
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "HH:mm"));
            commentVo.setHasLiked(quanZiApi.queryUserIsLike(user.getId(), commentVo.getId())?1:0);
            for (UserInfo userInfo : userInfos) {
                if(ObjectUtil.equals(record.getUserId(), userInfo.getUserId())){

                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            commentVos.add(commentVo);
        }
         pageResult.setItems(commentVos);
        return pageResult;


    }



    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Publish> pageInfo = quanZiApi.queryAlbumList(userId, page, pageSize);
        if(CollUtil.isEmpty(pageInfo.getRecords())){
            return pageResult;
        }

        //填充数据
        pageResult.setItems(this.fillQuanZiVo(pageResult,pageInfo.getRecords()).getItems());

        return pageResult;



    }

    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.getuser();
        List<Visitors> visitorsList = this.visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }
}
